package com.bkhc.product.api;

import com.bkhc.common.annotation.ApiOperation;
import com.bkhc.common.annotation.ApiPackage;
import com.bkhc.common.annotation.AuditLog;
import com.bkhc.common.annotation.WebRestController;
import com.bkhc.common.enu.OperationEnum;
import com.bkhc.common.util.ExcelUtil;
import com.bkhc.common.util.response.PageUtil;
import com.bkhc.common.util.response.ResultJson;
import com.bkhc.common.vo.OrderItemVo;
import com.bkhc.common.vo.OrderVo;
import com.bkhc.product.bo.OrderB0;
import com.bkhc.product.entity.GoodsSpec;
import com.bkhc.product.service.OrderService;
import com.bkhc.product.vo.OrderItem;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author pcq
 * @date 2021/6/20 17:57
 */
@WebRestController("")
@Api("订单管理服务")
@RequestMapping("/order")
@ApiPackage(code="order-api",name="订单管理服务",description = "后台订单管理服务操作接口")
public class OrderController extends CommonController{
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
    @Autowired
    private OrderService orderSerivce;

    @ApiOperation(code="queryOrder",name="产品合伙人查看转交的订单",description = "产品合伙人查看转交的订单",type = "common")
    @AuditLog(object="Order",operation = "查询订单",type = OperationEnum.query)
    @RequestMapping(path = "list/productor/{pageNum}/{pageSize}",method = RequestMethod.POST)
    public ResultJson<?> getOrders(@RequestBody(required=false) OrderVo order,
                                   @PathVariable(name="pageNum") int pageNum,
                                   @PathVariable(name="pageSize") int pageSize) {
        if(order == null){
            order = new OrderVo();
        }
        ResultJson<?> res = orderSerivce.getOrders(order, pageNum, pageSize);
        return res;
    }
    @ApiOperation(code="updateOrderStatuscomplate",name="产品合伙人确定订单完成",description = "产品合伙人确定订单完成",type = "common")
    @AuditLog(object="Order",operation = "产品合伙人确定订单完成",type = OperationEnum.query)
    @RequestMapping(path = "{orderCode}/complate",method = RequestMethod.POST)
    public ResultJson<?> complateOrder(@PathVariable(name="orderCode") String orderCode
                                  ) {
        ResultJson<?> res = orderSerivce.complateOrder(orderCode);
        return res;
    }

    @ApiOperation(code="updateOrderStatusfail",name="产品合伙人销毁订单",description = "产品合伙人销毁订单",type = "common")
    @AuditLog(object="Order",operation = "产品合伙人确定订单完成",type = OperationEnum.query)
    @RequestMapping(path = "{orderCode}/cancel",method = RequestMethod.POST)
    public ResultJson<?> cancelOrder(@PathVariable(name="orderCode") String orderCode
    ) {
        ResultJson<?> res = orderSerivce.cancelOrder(orderCode);
        return res;
    }
    @ApiOperation(code="queryOrderItem",name="查询订单Item",description = "查询订单Item")
    @AuditLog(object="OrderItem",operation = "查询订单Item",type = OperationEnum.query)
    @RequestMapping(path = "item",method = RequestMethod.POST)
    public ResultJson<List<OrderItemVo>> getOrdersItem(@RequestParam(name="orderCode") String orderCode) {
        List<OrderItemVo> res = orderSerivce.queryOrderItem(orderCode);
        ResultJson<List<OrderItemVo>> resultJson = ResultJson.success();
        resultJson.setData(res);
        return resultJson;
    }

    @ApiOperation(code="queryOrderByUserId",name="登陆用户查询订单",description = "登陆用户查询订单",type = "common")
    @AuditLog(object="Order",operation = "查询订单",type = OperationEnum.query)
    @RequestMapping(path = "/queryOrderByUserId",method = RequestMethod.POST)
    public ResultJson<?> queryOrderByUserId(@RequestBody OrderVo orderVo,
                                       @RequestParam(name="pageIndex") int pageIndex,
                                       @RequestParam(name="pageSize") int pageSize) {
        ResultJson res = orderSerivce.queryOrderByUserId(orderVo,pageIndex, pageSize);
        return res;
    }


    @ApiOperation(code="downloadOrderItem",name="下载订单Item",description = "下载订单Item")
    @AuditLog(object="OrderItem",operation = "下载订单Item",type = OperationEnum.query)
    @RequestMapping(path = "download",method = RequestMethod.POST)
    public void downloadOrdersItem(@RequestParam(name="orderCode") String orderCode, HttpServletResponse response) {
        List<OrderItemVo> res = orderSerivce.queryOrderItem(orderCode);
        List<OrderB0> bos = buildBo(res);
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=order");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ExcelUtil.generateExcel(bos,out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            }catch (Exception e) {
                logger.error("responseFileStream stream close() error:" + e.toString());
            }
        }

    }

    private List<OrderB0> buildBo(List<OrderItemVo> res) {
        return null;
    }

    @ApiOperation(code="buildOrder",name="生成订单",description = "生成订单",type = "common")
    @AuditLog(object="Order",operation = "生成订单",type = OperationEnum.query)
    @RequestMapping(path = "/buildOrder",method = RequestMethod.POST)
    public void buildOrder(@RequestBody Map orderinfo) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        List<Map<String,Object>> map = (List<Map<String,Object>>)orderinfo.get("orderItemList");
        List<OrderItem> oderitems = new ArrayList<>();
        for(Map<String,Object> entity:map){
            OrderItem tem = new OrderItem();
            tem.setPrice(new BigDecimal((Integer) entity.get("price")));
            tem.setCount(new BigDecimal((Integer) entity.get("count")));
            tem.setBrandCode(entity.get("brandCode").toString());
            tem.setProductCode(entity.get("productCode").toString());
            tem.setNum(Integer.parseInt(entity.get("num").toString()));
            Set<String> keySet = entity.keySet();
            List<GoodsSpec> goodsSpecList = new ArrayList<>();
            for(String key:keySet){
                if(key.startsWith("spec")){
                    GoodsSpec gs = new GoodsSpec();
                    String specdes = entity.get(key).toString();
                    String[] specs = specdes.split(":");
                    gs.setSpecName(specs[0]);
                    gs.setSpecValue(specs[1]);
                    goodsSpecList.add(gs);
                }
            }
            tem.setGoodsSpecList(goodsSpecList);
            oderitems.add(tem);
        }
        List<OrderItem> items = orderSerivce.buildOrder(oderitems);
        if(!CollectionUtils.isEmpty(items)){
            String productCode = items.get(0).getProductCode();
            List<String> head = Arrays.asList( "品牌","产品名称","规格","单价","数量","合计");
            List<List<Object>> data = new ArrayList<>();
            BigDecimal count = new BigDecimal(0);
            for(OrderItem item:items){
                List<Object> line = new ArrayList<>();
                line.add(item.getBrandName());
                line.add(item.getProductName());
                String sb = null;
                List<GoodsSpec> goodspesList = item.getGoodsSpecList();
                for(GoodsSpec gs:goodspesList){
                    if(!StringUtils.isEmpty(sb)){
                        sb=sb+"/"+gs.getSpecName()+":"+gs.getSpecValue();
                    }else{
                        sb = gs.getSpecName()+":"+gs.getSpecValue();
                    }

                }
                line.add(sb);
                line.add(item.getPrice().doubleValue()+"");
                line.add(item.getNum()+"");
                line.add(item.getCount().doubleValue()+"");
                count = count.add(item.getCount());
                data.add(line);
            }
            data.add(Arrays.asList("","","","","",count.doubleValue()+""));
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=order.xlsx");
            ServletOutputStream out = null;
            try {
                out = response.getOutputStream();
                ExcelUtil.writeExcelNoMapping(data,out,head);
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }



//        ResultJson<List<OrderItemVo>> resultJson = ResultJson.success();
//        resultJson.setData(res);
    }
}
